<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use think\Request;

class Product extends Backend
{
	
	public function product(){
		
		// 查询商品表
		
		$Productlist = model('Product.Product')->order('id desc')->paginate(7,false,['query' => Request::instance()->param()]);
		
		return $this->fetch('',[
			
			'Productlist' => $Productlist
			
		]);
		
	}
	
	// 查看删除的商品
	public function prorestore(){
		// whereNotNull('belong')  'deletetime', 'is not null'
		$restorelist = model('Product.Product')->onlyTrashed()->paginate(7,false,['query' => Request::instance()->param()]);
		
		return $this->fetch('',[
			
			'restorelist' => $restorelist
			
		]);
		
	}
	
	// 恢复删除的商品
	public function restore(){
		
		if($this->request->isAjax()){
			
			// 获取启动数据
			$arrstr = $this->request->param('str');
			
			// 字符串转数组
			$arr = explode(',',$arrstr);
			
			$data = [];
			
			// 循环
			foreach($arr as $item){
				$data[] = [
					'id' => $item,
					'deletetime' => null
				];
			}
			
			$result = model('Product.Product')->isUpdate(true)->saveAll($data);
			
			if($result === FALSE)
			{
				$this->error('恢复失败');	
			}else{
				// cookie('LoginUser',null);
				$this->success('恢复成功',url('admin/product/prorestore'),null,0);
			}
			
		}
		
	}
	
	// add商品添加
	public function productadd()
	{
		// 查询商品分类表
		$Typelist = model('Product.Type')->select();
		
		// 获取表单请求过来的数据
		if($this->request->isPost()){
			//get post
			$params = $this->request->param();
			 
			// 封装插入数据库的数组
			 $data = [
			    'typeid' => $params['typeid'],
				'name' => $params['name'],
				'price' => $params['price'],
				'stock' => $params['stock'],
				'content' => $params['content'],
				'flag' => $params['flag']
			];
			// 图片数组
			$thum = [];
			// 1
			if(isset($_FILES['thumbs']) && $_FILES['thumbs']['size'] > 0)
			{
			    $thumbs = upload('thumbs');
			
			    if($thumbs['code'] == 0)
			    {
			        $this->error($thumbs['msg']);
			    }
			
			    $thum['thumbs'] = '"'.substr($thumbs['data'],1,999).'"';
			}
			// 2
			if(isset($_FILES['thumbss']) && $_FILES['thumbss']['size'] > 0)
			{
			    $thumbs = upload('thumbss');
			
			    if($thumbs['code'] == 0)
			    {
			        $this->error($thumbs['msg']);
			    }
			
			    $thum['thumbss'] = '"'.substr($thumbs['data'],1,999).'"';
			}
			// 3
			if(isset($_FILES['thumb']) && $_FILES['thumb']['size'] > 0)
			{
			    $thumbs = upload('thumb');
			
			    if($thumbs['code'] == 0)
			    {
			        $this->error($thumbs['msg']);
			    }
			
			    $thum['thumb'] = '"'.substr($thumbs['data'],1,999).'"';
			}
			
			// 切割数组
			$thumStr = implode(",",$thum);
			
			// 多图放进数组 
			$data['thumbs'] = "[".$thumStr."]";
			
			// 验证
			$result = model('Product.Product')->validate('common/Product/Product')->save($data);
			
			if($result === FALSE)
			{
			    if(isset($_FILES['thumbs']) && $_FILES['thumbs']['size'] > 0)
			    {
			        @is_file('.' . $thum['thumbs']) && unlink('.' . $thum['thumbs']);
			    }
				
				if(isset($_FILES['thumbss']) && $_FILES['thumbss']['size'] > 0)
				{
				    @is_file('.' . $thum['thumbss']) && unlink('.' . $thum['thumbss']);
				}
				
				if(isset($_FILES['thumb']) && $_FILES['thumb']['size'] > 0)
				{
				    @is_file('.' . $thum['thumb']) && unlink('.' . $thum['thumb']);
				}
			
			    $this->error('添加失败');
			
			}else{
				
			    $this->success('添加成功','/admin/product/product');
				
			}
			
		}
		// 输出视图
		// 动态使用模板布局
		// $this->view->engine->layout(false);
		return $this->fetch('',[
			'Typelist' => $Typelist
		]);
	}
	
	// 编辑
	public function upproduct()
	{
		// id
		$id = $this->request->param('id');
		
		// 查询
		$Product = model('Product.Product')->find($id);
		
		// 查询商品分类表
		$Typelist = model('Product.Type')->select();
		
		// 查询域名
		$SiteUrl = model('Config')->where(['id'=>'9'])->find();
		
		// 获取表单请求过来的数据
		if($this->request->isPost()){
			//get post
			$params = $this->request->param();
			
			$Product = model('Product.Product')->where('id',$id)->find();
			
			if(!$Product)
			{
				$this->error('该商品不存在');
			}
			 
			 // 封装插入数据库的数组
			 $data = [
				'id' => $id,
				'typeid' => $params['typeid'],
			    'name' => $params['name'],
				'price' => $params['price'],
				'stock' => $params['stock'],
				'content' => $params['content'],
				'flag' => $params['flag']
			];
			
			// 存放的商品图片数组
			$thumbs = [];
			
			if(!empty($_FILES))
			{
			    foreach($_FILES as $key => $item)
			    {
			        if($_FILES[$key]['error'] != 0 || $_FILES[$key]['size'] <= 0)
			        {
			            continue;
			        }
			
			        $file = upload($key);
					
					if($file['code'] == 0)
					{
					    $this->error($file['msg']);
					}
			
			        $thumbs[] = [
						'key' => $key,
						'img' => $file['data']
					];
			
			    }
				
				// 多图数组
				$thumbsArr = json_decode($Product['thumbs'],true);	
								
				// 删除本地图片
				foreach($thumbsArr as $key => $item)
				{
					foreach($thumbs as $keys => $items)
					{
						if($key == $items['key'])
						{
							//字符串替换
							$thumb = str_replace($SiteUrl['value'], '', $item);
							// 删除本地
							@is_file('.' . '/' . $thumb) && unlink('.' . '/' . $thumb);
							// 重新组装数据
							$thumbsArr[$key] = substr($items['img'],1,999);
						}
					}
				}
				
				$Arr = [];
				
				foreach($thumbsArr as $key => $item)
				{
					$Arr[] = '"'. $item .'"';
				}
				
				// 切割数组
				$thumStr = implode(",",$Arr);
				
				$data['thumbs'] = "[".$thumStr."]";
			}
			
			// 修改
			$result = model('Product.Product')->isUpdate(true)->save($data);
			
			if($result === FALSE)
			{
			    $this->error('修改失败');
			
			}else{
			    
			    $this->success('修改成功','/admin/product/Product');
				
			}
			
		}
		
		return $this->fetch('',[
			
			'Product' => $Product,
			
			'Typelist' => $Typelist
			
		]);
	}
	
	// 删除商品
	public function delproduct()
	{
		if($this->request->isAjax())
		{
			// id
			$id = $this->request->param('id');
			
			// 批量删除
			$str = $this->request->param('str');
			
			if(!empty($id))
			{
				// 查询
				$Product = model('Product.Product')->find($id);
				
				if(!$Product)
				{
					$this>error('删除失败，该商品不存在');
				}
				
				$result = model('Product.Product')->destroy($id);
				
				if($result === FALSE)
				{
					$this->error('删除失败');
					
				}else{
					
					$this->success('删除成功','/admin/product/Product');
				}
			}
			
			if(!empty($str))
			{
				// 查询
				$Product = model('Product.Product')->whereIn('id',$str)->select();
				
				if(!$Product)
				{
					$this>error('删除失败，该商品不存在');
				}
				
				$result = model('Product.Product')->destroy($str);
				
				if($result === FALSE)
				{
					
				    $this->error('删除失败');
				
				}else{
									
				    $this->success('删除成功','/admin/product/product');
					
				}
				
			}
			
		}
		
	}
	
	public function type(){
		
		// 查询商品分类表
		
		$Typelist = model('Product.Type')->order('weigh desc')->paginate(7,false,['query' => Request::instance()->param()]);
		
		return $this->fetch('',[
			
			'Typelist' => $Typelist
			
		]);
		
	}
	
	// add产品分类添加
	public function typeadd()
	{
		// 获取表单请求过来的数据
		if($this->request->isPost()){
			//get post
			$params = $this->request->param();
			
			$type = model('Product.Type')->where('name',$params['name'])->find();
			
			if($type)
			{
				$this->error('该产品分类昵称已经存在');
			}
			 
			 // 封装插入数据库的数组
			 $data = [
			    'name' => $params['name'],
			    'weigh' => $params['weigh']
			];
			
			if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0)
			{
			    $cover = upload('cover');
			
			    if($cover['code'] == 0)
			    {
			        $this->error($cover['msg']);
			    }
			
			    $data['cover'] = $cover['data'];
			}
			
			// 验证
			$result = model('Product.Type')->validate('common/Product/Type')->save($data);
			
			if($result === FALSE)
			{
			    if(isset($data['cover']) && $_FILES['cover']['size'] > 0)
			    {
			        @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
			    }
			
			    $this->error('添加失败');
			
			}else{
				
			    if(isset($data['cover']) && $_FILES['cover']['size'] > 0)
			    {
			        @is_file('.' . $type['cover']) && unlink('.' . $type['cover']);
			    }
				
			    $this->success('添加成功','/admin/product/type');
				
			}
			
		}
		// 输出视图
		// 动态使用模板布局
		// $this->view->engine->layout(false);
		return $this->fetch();
	}
	
	// 编辑
	public function uptype()
	{
		// id
		$id = $this->request->param('id');
		
		// 查询
		$Type = model('Product.Type')->find($id);
		
		// 获取表单请求过来的数据
		if($this->request->isPost()){
			//get post
			$params = $this->request->param();
			
			$type = model('Product.Type')->where('name',$params['name'])->find();
			
			if(!$type)
			{
				$this->error('该产品分类不存在');
			}
			 
			 // 封装插入数据库的数组
			 $data = [
				'id' => $id,
			    'name' => $params['name'],
			    'weigh' => $params['weigh']
			];
			
			if(isset($_FILES['cover']) && $_FILES['cover']['size'] > 0)
			{
			    $cover = upload('cover');
			
			    if($cover['code'] == 0)
			    {
			        $this->error($cover['msg']);
			    }
			
			    $data['cover'] = $cover['data'];
			}
			
			// 修改
			$result = model('Product.Type')->validate('common/Product/Type')->isUpdate(true)->save($data);
			
			if($result === FALSE)
			{
			    if(isset($data['cover']) && $_FILES['cover']['size'] > 0)
			    {
			        @is_file('.' . $data['cover']) && unlink('.' . $data['cover']);
			    }
			
			    $this->error('修改失败');
			
			}else{
				
			    if(isset($data['cover']) && $_FILES['cover']['size'] > 0)
			    {
			        @is_file('.' . $type['cover']) && unlink('.' . $type['cover']);
			    }
				
			    $this->success('修改成功','/admin/product/type');
				
			}
			
		}
		
		return $this->fetch('',[
			
			'Type' => $Type
			
		]);
	}
	
	// 删除分类
	public function deltype()
	{
		if($this->request->isAjax())
		{
			// id
			$id = $this->request->param('id');
			
			// 批量删除
			$str = $this->request->param('str');
			
			if(!empty($id))
			{
				// 查询
				$Type = model('Product.Type')->find($id);
				
				if(!$Type)
				{
					$this>error('删除失败，该产品分类不存在');
				}
				
				$result = model('Product.Type')->where('id',$id)->delete();
				
				if($result === FALSE)
				{
					@is_file('.' . $Type['cover']) && unlink('.' . $Type['cover']);
					$this->error('删除失败');
					
				}else{
					@is_file('.' . $Type['cover']) && unlink('.' . $Type['cover']);
					$this->success('删除成功','/admin/product/type');
				}
			}
			
			if(!empty($str))
			{
				// 查询
				$Type = model('Product.Type')->whereIn('id',$str)->select();
				
				if(!$Type)
				{
					$this>error('删除失败，该产品分类不存在');
				}
				
				$result = model('Product.Type')->whereIn('id',$str)->delete();
				
				if($result === FALSE)
				{
					foreach($Type as $item)
					{
						@is_file('.' . $item['cover']) && unlink('.' . $item['cover']);
					}
				
				    $this->error('删除失败');
				
				}else{
					
					foreach($Type as $item)
					{
						@is_file('.' . $item['cover']) && unlink('.' . $item['cover']);
					}
									
				    $this->success('删除成功','/admin/product/type');
					
				}
				
			}
			
		}
		
	}
}
